<template>
  <div class="private-letter-main">
    <el-drawer v-model="show" :title="`【${props.id}】私信清单`" size="800px" custom-class="preview_form_body">
      <div class="message-box">
        <div class="message-box-item">
          <div class="msg-title">私信消息总数</div>
          <div class="msg-num">{{ baseInfo.total_data }}</div>
        </div>
        <div class="message-box-item">
          <div class="msg-title">已发送消息数</div>
          <div class="msg-num">{{ baseInfo.success_data }}</div>
        </div>
        <div class="message-box-item">
          <div class="msg-title">未发消息数</div>
          <div class="msg-num">{{ baseInfo.no_data }}</div>
        </div>
      </div>
      <div class="search-box">
        <el-form :inline="true" :model="form" label-width="100px">
          <el-form-item label="客户信息">
            <el-input v-model="form.name" clearable placeholder="请输入客户姓名|昵称搜索"></el-input>
          </el-form-item>
          <el-form-item label="发送状态：">
            <el-select v-model="form.sendStatus" clearable placeholder="请选择发送状态">
              <el-option v-for="item in sendStatus" :key="item.code" :label="item.label" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="searchTable()">查询</el-button>
      </div>
      <div class="btn-list">
        <el-button type="primary" v-if="props.tabActiveType == '3'" @click="handlerPreview">消息预览</el-button>
        <!-- <el-button type="primary" @click="handlerSendMsg('1')">批量发送</el-button> -->
        <el-popover v-if="props.tabActiveType == '3'" placement="top-start" :width="190" trigger="hover">
          <el-button size="small" type="primary" @click="handlerSendMsg('3')">全量发送</el-button>
          <el-button size="small" type="primary" @click="handlerSendMsg('1')">批量发送</el-button>
          <template #reference>
            <el-button type="primary">发送</el-button>
          </template>
        </el-popover>
        <el-button v-else type="primary" @click="handlerSendMsg('3')">全量发送</el-button>
      </div>
      <div class="table-box">
        <el-table :data="tableData" style="width: 100%" @selection-change="handlerSelectionChange">
          <el-table-column type="selection"></el-table-column>
          <el-table-column width="160px" prop="title" :label="labelCustomerText">
            <template #default="scope">
              <div class="customer-info">
                <el-image class="customer-info-img" :src="scope.row.AvatarUrl">
                  <template #error>
                    <img v-if="labelCustomerText == '客户信息'" class="customer-info-img"
                      src="@renderer/assets/img/user.png" alt="" />
                    <img v-else class="customer-info-img" src="@renderer/assets/img/group_avatar.png" alt="" />
                  </template>
                </el-image>
                <div class="customer-info-name" v-if="scope.row.Name || scope.row.Nickname">{{ scope.row.Name }}<span
                    v-if="scope.row.Nickname">({{ scope.row.Nickname }})</span></div>
                <div class="customer-info-name" v-else>(无名称)</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="SendStatus" label="发送状态">
            <template #default="scope">
              <div>
                {{ getListName(setStatusList, scope.row.SendStatus) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="SendTime" label="发送时间" />
          <el-table-column prop="ErrMsg" label="失败原因" :show-overflow-tooltip="true" />
          <el-table-column prop="address" label="操作" fixed="right" width="160px" v-if="props.tabActiveType == '3'">
            <template #default="scope">
              <el-button v-if="!scope.row.ObjId" size="small" @click="handleToMatch(scope.row)">绑定</el-button>
              <el-button v-else-if="scope.row.AllowChangeBind" size="small" @click="handleToMatch(scope.row)">换绑</el-button>
              <el-button v-if="(scope.row.SendStatus == 3 || scope.row.SendStatus == 4)" size="small"
                @click="handlerSendMsg('2', scope.row)">
                {{ scope.row.SendStatus == 4 ? '重新发送' : '发送' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination layout="total,  prev, pager, next,sizes, jumper" :current-page="searchForm.page"
          :page-size="searchForm.page_size" :page-sizes="[15, 30, 50, 100]" :total="searchForm.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-drawer>
    <el-drawer v-model="phoneShow" title="消息预览" size="30%" custom-class="preview_form_body">
      <div class="phone-box">
        <div class="phone-box-content">
          <div class="phone-box-content-con">
            <div class="phone-title">详情</div>
            <el-scrollbar class="phone-scrollbar">
              <div class="phone-msg">
                <div class="phone-msg-item user_con" v-for="item in phoneMsgList" :key="item">
                  <div class="friend_main">
                    <!--文本-->
                    <template v-if="item.Type == 0">
                      <div class="welcomeWords">{{ item.Content }}</div>
                    </template>
                    <!-- 图片 -->
                    <template v-if="item.Type == 1">
                      <el-image class="send_image" :src="item.Url" alt="" fit="cover">
                        <template #error>
                          <img class="send_image" src="@renderer/assets/imgs/file/pic.png" alt="" />
                        </template>
                      </el-image>
                    </template>
                    <!-- 音频 -->
                    <template v-else-if="item.Type == 4">
                      <div class="user_file">
                        <div class="user_file_main">
                          <div class="user_file_desc">{{ item.FileName }}</div>
                          <img class="user_file_icon" src="@renderer/assets/imgs/file/mp3.png" alt="" />
                        </div>
                      </div>
                    </template>
                    <!-- 视频 -->
                    <template v-else-if="item.Type == 2">
                      <div class="video_list">
                        <el-image class="video_image" :src="getVideoImage(item.Url, 80, 55)" alt=""
                          fit="cover"></el-image>
                        <img class="video_play" src="@renderer/assets/imgs/file/play.png" alt="" />
                      </div>
                    </template>
                    <!-- 文件 -->
                    <template v-else-if="item.Type == 5">
                      <div class="user_file">
                        <div class="user_file_main">
                          <div class="user_file_desc">{{ item.FileName }}</div>
                          <img class="user_file_icon" :src="getSuffixIcon(item.Url)" alt="" />
                        </div>
                      </div>
                    </template>
                    <!-- 链接 -->
                    <template v-if="item.Type == 3">
                      <div class="user_link">
                        <div class="user_link_tit">{{ item.LinkTitle }}</div>
                        <div class="user_link_main">
                          <div class="user_link_desc"></div>
                          <el-image :src="item.ThumbUrl" alt="" class="user_link_icon" fit="cover">
                            <template #error>
                              <el-image class="user_link_icon" src="@renderer/assets/imgs/file/pic.png"
                                alt=""></el-image>
                            </template>
                          </el-image>
                        </div>
                      </div>
                    </template>
                    <!-- 电商素材--电商产品  -->
                    <template v-if="item.Type == 7">
                      <div class="user_link">
                        <div class="user_link_tit">{{ item.LinkTitle }}</div>
                        <div class="user_link_main">
                          <div class="user_link_desc">{{ item.Content }}</div>
                          <el-image :src="item.ThumbUrl" alt="" class="user_link_icon" fit="cover">
                            <template #error>
                              <el-image class="user_link_icon" src="@renderer/assets/imgs/file/shop.png"
                                alt=""></el-image>
                            </template>
                          </el-image>
                        </div>
                      </div>
                    </template>
                    <!-- 电商素材-- 页面素材  -->
                    <template v-if="item.Type == 8">
                      <div class="user_link">
                        <div class="user_link_tit">{{ item.LinkTitle }}</div>
                        <div class="user_link_main">
                          <div class="user_link_desc">{{ item.Content }}</div>
                          <el-image :src="item.ThumbUrl" alt="" class="user_link_icon" fit="cover">
                            <template #error>
                              <el-image class="user_link_icon" src="@renderer/assets/imgs/file/shop.png"
                                alt=""></el-image>
                            </template>
                          </el-image>
                        </div>
                      </div>
                    </template>
                    <!-- 抽奖 -->
                    <template v-if="item.Type == 6">
                      <div class="user_link">
                        <div class="user_link_tit">{{ item.LinkTitle }}</div>
                        <div class="user_link_main">
                          <div class="user_link_desc">{{ item.Content }}</div>
                          <el-image :src="item.ThumbUrl" alt="" class="user_link_icon" fit="cover">
                            <template #error>
                              <el-image class="user_link_icon" src="@renderer/assets/imgs/file/wbgg.png"
                                alt=""></el-image>
                            </template>
                          </el-image>
                        </div>
                      </div>
                    </template>
                    <!-- 收集表 -->
                    <template v-if="item.Type == 9">
                      <div class="user_link">
                        <div class="user_link_tit">{{ item.LinkTitle }}</div>
                        <div class="user_link_main">
                          <div class="user_link_desc">{{ item.Content }}</div>
                          <el-image :src="item.ThumbUrl" alt="" class="user_link_icon" fit="cover">
                            <template #error>
                              <el-image class="user_link_icon" src="@renderer/assets/imgs/file/form.png"
                                alt=""></el-image>
                            </template>
                          </el-image>
                        </div>
                      </div>
                    </template>
                    <!-- 公众号图文 -->
                    <template v-else-if="item.Type == 10">
                      <div class="user_file">
                        <div class="user_file_main">
                          <div class="user_file_desc">{{ item.LinkTitle }}</div>
                          <el-image :src="item.ThumbUrl" alt="" class="user_file_icon" fit="contain"></el-image>
                        </div>
                      </div>
                    </template>
                    <!-- 小程序素材 -->
                    <template v-else-if="item.Type == 11">
                      <div class="miniApp">
                        <div class="mini_box">
                          <img class="mini_icon" src="@renderer/assets/imgs/wxapp/Appletbg.png" alt="" />
                          <div class="miniName">{{ item.LinkTitle }}</div>
                        </div>
                        <div class="mini_bg">
                          <el-image :src="item?.ThumbUrl" alt="" class="miniImg" fit="contain">
                            <template #error>
                              <div class="image-slot">
                                <img :src="miniAppImg" alt="" />
                              </div>
                            </template>
                          </el-image>
                        </div>
                        <div class="mini_bot">
                          <img src="@renderer/assets/imgs/wxapp/Applet.png" alt="" />
                          <span>小程序</span>
                        </div>
                      </div>
                    </template>
                  </div>
                </div>
              </div>
            </el-scrollbar>
          </div>
        </div>
      </div>
    </el-drawer>
    <el-dialog v-model="matchVisabled" draggable title="绑定客户" width="640px">
      <div class="cust_info">
        <el-avatar shape="square" :size="50" :src="currentCust.AvatarUrl || 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png'" />
        <div>{{ currentCust.Name }}{{ currentCust.Nickname ? `(${currentCust.Nickname})` : '' }}</div>
      </div>
      <div class="main-color">匹配到以下{{ matchList.length }}个客户：</div>
      <div class="matched_info_list">
        <div v-for="item in matchList" :key="item.scrmCustId" class="matched_info_item"
          :class="{ active: item.isCurrentMatch }">
          <el-avatar shape="square" :size="46" :src="item.avatar" />
          <div class="match_cust_info">
            <div class="ellipsis-1">{{ item.name }}<span v-if="item.remarkName">（{{ item.remarkName }}）</span></div>
            <div class="main-color ellipsis-1 ">{{ item.sourceInfo }}</div>
            <div class="ellipsis-1">添加时间：{{ item.addTime }}</div>
          </div>
          <el-button v-if="item.isCurrentMatch" size="small" disabled>当前客户</el-button>
          <el-button v-else size="small" @click="toMatchCustInfo(item)">绑定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { getVideoImage, getSuffixIcon } from '@renderer/utils/utils'
import {
  massDispatchBaseInfo,
  massDispatchDetail,
  massDispatchPreview,
  massDispatchDetailSend,
  toMatchCustwxWork,
  toMatchCustGroupwxWork,
  toSubmitMatchCustInfo
} from '@renderer/ajax/api/groupMonitor'
import { ElMessage } from 'element-plus'
import miniAppImg from '@renderer/assets/imgs/file/miniApp.png'
import { store } from '@renderer/store'

const emit = defineEmits(['update:modelValue']);

interface Props {
  modelValue: any
  id: any,
  options: any,
  tabActiveType: any
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: {
    type: Boolean,
    default: false
  },
  id: {
    type: [String, Number],
    default: ''
  },
  tabActiveType: {
    type: [String, Number],
    default: ''
  },
  options: {},

})

const show = computed({
  get() {
    return props.modelValue;
  },
  set(val: any) {
    emit('update:modelValue', val);
  }
});

const phoneShow = ref<boolean>(false)

const labelCustomerText = ref<string>('客户信息')

const form = reactive<any>({
  name: '',
  sendStatus: ''
})

const searchForm = reactive<any>({
  page: 1,
  page_size: 15,
  total: 0
})

const selectList = ref<any>([])

const baseInfo = reactive<any>({
  no_data: 0,
  success_data: 0,
  total_data: 0,
})

const tableData = ref<any>([])

const sendStatus = reactive<any>([
  { label: '全部', code: 0 },
  { label: '已发送', code: 1 },
  { label: '发送中', code: 2 },
  { label: '未发送', code: 3 },
  { label: '发送失败', code: 4 }
])

const setStatusList = [
  { label: '全部', code: 0 },
  { label: '已发送', code: 1 },
  { label: '发送中', code: 2 },
  { label: '未发送', code: 3 },
  { label: '发送失败', code: 4 },
]

const getListName = (list: any, type: any) => {
  let info = list.find(el => el.code == type) || {}
  return info.label
}

const phoneMsgList = ref<any>([])

const handlerQuery = () => {

}

const handlerClick = () => {

}

const searchTable = () => {
  getBaseInfo()
  getTableList()
}

const handlerSendMsg = async (type: any, val?: any) => {
  let Ids = []
  if (type == '1') {
    if (!selectList.value.length) {
      ElMessage.warning('请选择需要重新发送的数据')
      return
    }
    Ids = selectList.value.map(el => el.Id)
  } else if (type == '2') {
    Ids = [val.Id]
  } else if (type == '3') {
    Ids = []
  }
  let params = {
    MessId: props.id,
    Ids: Ids
  }
  let res = await massDispatchDetailSend(params)
  ElMessage.success('发送任务提交成功')
  getTableList()
  getBaseInfo()
}

const handlerPreview = () => {
  phoneShow.value = true
}

const handlerSelectionChange = (val: any) => {
  selectList.value = val || []
}

const getBaseInfo = async () => {
  let res: any = await massDispatchBaseInfo({ Id: props.id })
  baseInfo.no_data = res.no_data
  baseInfo.success_data = res.success_data
  baseInfo.total_data = res.total_data

}

const getTableList = async () => {
  let params = {
    Id: props.id,
    SendStatus: form.sendStatus,
    CustInfo: form.name,
    Page: searchForm.page,
    PageSize: searchForm.page_size
  }
  let res: any = await massDispatchDetail(params)
  console.log(res, '2')

  tableData.value = res?.Data || []
  searchForm.total = res?.Total || 0
  if (res.Data && res.Data[0]) {
    if (res.Data[0]?.Type == 1) {
      labelCustomerText.value = '客户信息'
    } else if (res.Data[0]?.Type == 2) {
      labelCustomerText.value = '客户群信息'
    }
  }
}

const getPreviewInfo = async () => {
  let params = {
    id: props.id
  }
  let res = await massDispatchPreview(params)
  phoneMsgList.value = res || []
}

const handleSizeChange = (val: number) => {
  searchForm.page_size = val
  getTableList()
}

const handleCurrentChange = (val: number) => {
  searchForm.page = val
  getTableList()
}

watch(show, (val) => {
  if (val) {
    form.sendStatus = ''
    form.name = ''
    getBaseInfo()
    getTableList()
  }
})

watch(phoneShow, (val) => {
  console.log(val, 'xx')
  if (val) {
    getPreviewInfo()
  }
})


const matchVisabled = ref(false)
const matchList = reactive([])
const userId = store.getters['common/userId']
const currentCust = reactive<any>({})
const handleToMatch = async (item) => {
  console.log('item: ', item);
  Object.assign(currentCust, item)
  try {
    const res: any = await (item.Type === 1 ? toMatchCustwxWork : toMatchCustGroupwxWork)({
      userId: userId,
      wxUserId: item.ScrmId,
      massDataId: item.MassDataId
    })
    const { data } = res
    if (Array.isArray(data)) {
      if (data.length <= 0) {
        return ElMessage.warning('暂无匹配到' + (item.Type === 1 ? '客户' : '客户群'))
      }
      matchVisabled.value = true
      matchList.splice(0, matchList.length, ...data)
    }
  } finally {

  }
}

const toMatchCustInfo = async (item) => {
  console.log('item: ', item);
  const params = {
    // 1是客户群，2是客户
    type: currentCust.Type === 1 ? 2 : 1, 
    userId: userId,
    conversationId: item.conversationId,
    scrmCustId: currentCust.ScrmId
  }
  await toSubmitMatchCustInfo(params)
  getTableList()
  matchVisabled.value = false
  ElMessage.success('客户绑定成功')
}

</script>
<style lang="scss" scoped>
.private-letter-main {
  .message-box {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .message-box-item {
      padding: 24px 36px;
      text-align: center;
      border-radius: 2px;
      border: 1px solid #e8e8e8;

      .msg-num {
        padding-top: 10px;
      }
    }
  }

  .search-box {
    margin: 24px 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .table-box {
    .customer-info {
      display: flex;
      align-items: center;

      .customer-info-img {
        flex:  0 0 30px;
        width: 30px;
        height: 30px;
      }

      .customer-info-name {
        margin-left: 12px;
      }
    }
  }

  .btn-list {
    margin: 0 0 16px;
    text-align: right;
  }

  .phone-box {
    height: 615px;
    display: flex;
    align-items: center;
    justify-content: center;

    .phone-box-content {
      height: 100%;
      margin: 0 auto;
      position: relative;
      width: 375px;
      // height: 410px;
      padding: 9px;
      background-color: #f3fafb;
      border: solid 2px #d2d8db;
      border-radius: 24px;

      .phone-box-content-con {
        background: #ffffff;
      }

      .phone-title {
        padding-top: 12px;
        text-align: center;
        line-height: 24px;
        font-size: 16px;
        border-radius: 20px 20px 0 0;
      }

      .phone-scrollbar {
        // width: 375px;
        width: 95%;
        height: 542px;
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        background: #ffffff;
        border-radius: 0 0 20px 20px;

        .phone-msg {
          .phone-msg-item {
            margin: 6px 20px;
            padding: 12px;
            background: #e8e8e8;
            border-radius: 4px;

            .item-img {
              width: 20px;
              height: 20px;
            }
          }
        }
      }
    }
  }

  .user_con {
    margin-top: 10px;
    display: flex;

    .user_avator {
      width: 22px;
      height: 22px;
      margin-right: 4px;
    }

    .friend_main {
      flex: 1;

      .user_name {
        font-size: 12px;
        font-family: STHeitiSC-Medium, STHeitiSC;
        font-weight: 500;
        color: #969696;
        transform: scale(0.6);
        transform-origin: left top;
        margin-bottom: 4px;
      }

      .welcomeWords {
        position: relative;
        margin-left: 5px;
        font-size: 12px;
        color: #969696;
        line-height: 15px;
        transform: scale(0.6);
        transform-origin: left top;
        width: 160px;
        box-sizing: border-box;
        word-break: break-all;
        overflow: hidden;
        padding: 5px 10px;
        background-color: #fff;
        border-radius: 5px;

        &::after {
          content: '';
          position: absolute;
          left: -5px;
          top: 10px;
          width: 0;
          height: 0;
          border-top: 5px solid transparent;
          border-right: 8px solid #fff;
          border-bottom: 5px solid transparent;
        }
      }

      .send_image {
        width: 68px;
        height: 46px;
      }

      .video_list {
        position: relative;
        width: 80px;
        height: 55px;

        .video_image {
          width: 100%;
          height: 100%;
        }

        .video_play {
          width: 15px;
          height: 15px;
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
        }
      }

      .user_link {
        margin-left: 5px;
        position: relative;
        width: 151px;
        height: 65px;
        box-sizing: border-box;
        padding: 5px 10px;
        border-radius: 5px;
        background: #ffffff;

        &::after {
          content: '';
          position: absolute;
          left: -5px;
          top: 10px;
          width: 0;
          height: 0;
          border-top: 5px solid transparent;
          border-right: 8px solid #fff;
          border-bottom: 5px solid transparent;
        }

        .user_link_tit {
          width: 100%;
          font-size: 12px;
          font-family: STHeitiSC-Light, STHeitiSC;
          font-weight: 300;
          color: #000000;
          transform: scale(0.83);
          transform-origin: left top;
        }

        .user_link_main {
          margin-top: 4px;
          display: flex;

          .user_link_desc {
            width: 110px;
            font-size: 12px;
            font-family: STHeitiSC-Light, STHeitiSC;
            font-weight: 300;
            color: #969696;
            transform: scale(0.6);
            transform-origin: left top;
            margin-top: 2px;
          }

          .user_link_icon {
            width: 22px;
            height: 22px;
          }
        }
      }

      .user_file {
        position: relative;
        margin-left: 5px;
        width: 150px;
        height: 48px;
        box-sizing: border-box;
        padding: 8px;
        border-radius: 3px;
        background: #ffffff;

        &::after {
          content: '';
          position: absolute;
          left: -5px;
          top: 6px;
          width: 0;
          height: 0;
          border-top: 5px solid transparent;
          border-right: 10px solid #fff;
          border-bottom: 5px solid transparent;
        }

        .user_file_main {
          display: flex;

          .user_file_desc {
            width: 100px;
            font-size: 12px;
            transform: scale(0.83);
            transform-origin: left top;
            margin-bottom: 6px;
            font-family: STHeitiSC-Light, STHeitiSC;
            font-weight: 300;
            color: #000000;
            overflow: hidden;
            overflow: hidden;
            white-space: wrap;
            text-overflow: ellipsis;
          }

          .user_file_icon {
            width: 30px;
            height: 30px;
          }
        }

        .user_file_size {
          // margin-top: 2px;
          font-family: STHeitiSC-Light, STHeitiSC;
          font-weight: 300;
          color: #969696;
          font-size: 12px;
          transform: scale(0.6);
          transform-origin: left top;
        }
      }

      .miniApp {
        width: 150px;
        height: 164px;
        background: #ffffff;
        position: relative;
        padding: 10px 5px 14px;
        box-sizing: border-box;

        .mini_box {
          display: flex;
          align-items: center;
          margin-bottom: 7px;
        }

        .mini_icon {
          width: 13px;
          height: 13px;
          margin-right: 4px;
        }

        .miniName {
          font-size: 12px;
          white-space: nowrap;
          overflow: hidden;
          color: #969696;
          text-overflow: ellipsis;
        }

        .mini_bg {
          text-align: center;
          padding-bottom: 5px;
          border-bottom: 1px solid #EAEAEA;
        }

        .mini_bot {

          img {
            width: 8px;
            height: 7px
          }

          span {
            display: inline-block;
            font-size: 12px;
            transform: scale(0.68)
          }
        }

        .miniImg {
          width: 100%;
          height: 106px;
          margin: 0 auto;
        }
      }
    }
  }
}

.matched_info_list {
  margin-top: 16px;
  display: grid;
  gap: 16px;
  grid-template-columns: repeat(2, 1fr);
  max-height: 466px;
  overflow-y: auto;

  .matched_info_item {
    display: grid;
    align-items: center;
    grid-template-columns: 46px 1fr 60px;
    border-radius: 8px;
    padding: 8px;
    border: 1px solid #ccc;

    &.active {
      border: 1px solid var(--main-color);
    }

    .match_cust_info {
      margin-left: 6px;
      font-size: 12px;
      display: flex;
      align-self: stretch;
      flex-direction: column;
      justify-content: space-between;
    }
  }

}

.cust_info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;

  .el-avatar {
    margin-right: 12px;
  }
}

.main-color {
  color: var(--main-color);
}
</style>